import { Hono } from 'hono'
import { serve } from 'bun'
import { WebSocketServer } from 'ws'
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { get as _get } from 'lodash'

const app = new Hono()

// 载入配置（兼容 zitmap_bad/config.json 结构）
const loadConfig = () => {
  try {
    const cfgPath = resolve(process.cwd(), '../zitmap_bad/config.json')
    return JSON.parse(readFileSync(cfgPath, 'utf8'))
  } catch (e) {
    return { RConf: { base: { port: 9090 } } }
  }
}

const Config = loadConfig()
const Port = _get(Config, 'RConf.base.port', 9090)

// 简单内存事件总线
const sockets = new Set()
const emitIO = (event, payload) => {
  const data = JSON.stringify({ event, payload })
  sockets.forEach(s => { try { s.send(data) } catch {} })
}

// 基础路由
app.get('/health', c => c.json({ ok: true, at: Date.now() }))
app.get('/config', c => c.json(Config))

// 兼容 client.call 风格：{ action, params }
app.post('/call', async c => {
  const { action, params } = await c.req.json().catch(() => ({}))
  // 占位：后续映射到 biz/proxy/slaver 实现
  if (action === 'ping') return c.json({ pong: true, params })
  return c.json({ error: 'unknown action', action })
})

// Bun 原生 HTTP + ws 协议升级
const server = serve({
  port: Port,
  fetch: app.fetch,
})

const wss = new WebSocketServer({ server })
wss.on('connection', (ws) => {
  sockets.add(ws)
  ws.send(JSON.stringify({ event: 'token', payload: Date.now() }))
  ws.on('message', (msg) => {
    // 简单转发：客户端可发送 {event, payload}
    try {
      const { event, payload } = JSON.parse(String(msg))
      emitIO(event, payload)
    } catch {}
  })
  ws.on('close', () => sockets.delete(ws))
})

console.log(`[services] Hono listening on http://localhost:${Port}`)

